<template>
  <div class="menu-out">
    <el-collapse v-model="activeNames" v-if="pageList.length > 0">
      <div v-for="(item, index) in pageList" :key="index">
        <el-collapse-item :name="index">
          <template slot="title">
            <div class="collapse-title flex-beiween-box">
              <span>{{ item.menuName }}</span>
              <div v-if="$route.query.key">
                <el-button size="mini" plain type="primary" class="normal-btn m-r-s" @click.stop="openDialog(item)">添加菜单</el-button>
              </div>
            </div>
          </template>
          <div class="form-box" v-for="(formItem, formIndex) in item.menuList" :key="formIndex">
            <el-form :ref="`form${formIndex}`" label-width="120px" :model="formItem">
              <el-row class="row">
                <el-col :span="7">
                  <el-form-item label="显示名称" prop="menuName" :rules="[{ required: true, message: '请输入显示名称', trigger: 'blur' }]">
                    <el-input v-model="formItem.menuName" placeholder="请输入" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="二级菜单">
                    <el-select v-model="formItem.secondLevelMenuList" collapse-tags clearable multiple>
                      <el-option v-for="item in formItem.secondLevelList" :key="item.primaryKey" :label="item.name" :value="item.primaryKey" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="所属左导航" prop="ifInMore" :rules="[{ required: true, message: '请选择所属左导航', trigger: '' }]">
                    <el-select v-model="formItem.ifInMore" clearable>
                      <el-option label="无" :value="0" />
                      <el-option v-for="leftMenu in item.leftMenuList" 
                                :key="leftMenu.menuId" 
                                :label="leftMenu.menuName" 
                                :value="Number(leftMenu.description ? leftMenu.description.split(':')[1] : 1)"/>
                          </el-select>
                        </el-form-item>
                      </el-col>
                <el-col :span="3">
                  <el-button size="mini" plain type="danger" class="f-right normal-btn item-btn m-l-s" @click="deleteMenu(formItem)">删除</el-button>
                  <el-button size="mini" plain type="primary" class="f-right normal-btn item-btn" @click="saveMenu(formItem)">保存</el-button>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <section class="null-page" v-if="item.menuList.length == 0">暂无数据！</section>
        </el-collapse-item>
      </div>
    </el-collapse>

    <el-dialog title="添加菜单" :visible.sync="menuDialog" width="70%" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <el-form ref="dialogForm" label-width="120px" :model="dialogFormModel">
        <el-row class="row">
          <el-col :span="24">
            <el-form-item label="原菜单" prop="secondMenu" :rules="[{ required: true, message: '请选择二级菜单', trigger: '' }]">
              <el-select v-model="dialogFormModel.secondMenu" filterable clearable @change="getSelectName">
                <el-option v-for="item in dialogmenuList" :key="item.primaryKey" :label="item.name" :value="item.primaryKey" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示名称" prop="menuName" :rules="[{ required: true, message: '请输入显示名称', trigger: 'blur' }]">
              <el-input maxlength="200" v-model="dialogFormModel.menuName" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="二级菜单" prop="secondLevelMenuList">
              <el-select v-model="dialogFormModel.secondLevelMenuList" filterable clearable multiple>
                <el-option v-for="item in secondMenuList" :key="item.primaryKey" :label="item.name" :value="item.primaryKey" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属左导航" prop="ifInMore" :rules="[{ required: true, message: '请选择所属左导航', trigger: '' }]">
              <el-select v-model="dialogFormModel.ifInMore" clearable>
                <el-option label="无" :value="0" />
                <el-option v-for="item in leftMenuList" 
                          :key="item.primaryKey" 
                          :label="item.name" 
                          :value="Number(item.description ? item.description.split(':')[1] : 1)"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取 消</el-button>
        <el-button size="small" type="primary" @click="confirmAddMenu">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import * as Port from "../../../api";
import { formValid } from '@/lib/utils'
import { apiMenuGroupTree,apiMenuGroupAdd,apiMenuGroupEdit,apiMenuGroupDel } from '../../../api';
import { requestTips,askDialog } from "../../../assets/util"

export default {
  data() {
    return {
      activeNames: 0,
      menuDialog:false,
      pageList: [],
      secondMenuList: [],//下拉框的数据源
      dialogmenuList:[],//添加菜单时的当前所有二级菜单
      leftMenuList: [],
      checkAll: false,//是否全选
      isIndeterminate: true,
      dialogFormModel:{
        secondMenu:"",
        menuName:"",
        secondLevelMenuList:[],
        ifInMore:0
      },
      currentChosrMenu:[]
    };
  },
  created() {
    // 获取默认的企业key
    if (!this.$route.query.key && localStorage.getItem('userEnterpriseid') && this.$route.query.isAdd != 1) {
      this.$route.query.key = localStorage.getItem('userEnterpriseid')
    }
  },

  mounted() {
    if (this.$route.query.key) {
      this.getInfo()
    }
  },

  methods: {
      //数据源
      async getInfo() {
        let res = await Port.apiMenuGroupTree({
          enterpriseid:this.$route.query.key
        })
        res.menuManageList.forEach(item=>{
          item.menuList.forEach(menu=>{
            menu.secondLevelMenuList = menu.secondLevelCheckedList
          })

          item.leftMenuList = item.menuList.filter((menu) => {
              return menu.description && menu.description.indexOf('leftMenu') > -1
          })
        })
        this.pageList = res.menuManageList || []
      },
      //弹框中的数据源
      async getDialogmenuList (param) {
        let res = await Port.apiMenuSonList({
          enterpriseid:this.$route.query.key,
          parentId:param.menuId
        })

        res.rows = res.rows || []

        this.leftMenuList = res.rows.filter((item) => {
            return item.description && item.description.indexOf('leftMenu') > -1
        })

        for (var i = 0,len = res.rows.length; i < len; i++) {
          let item = res.rows[i]
          if (item) {
            if (this.currentChosrMenu.indexOf(item.primaryKey) > -1) {
              res.rows.splice(i,1)
              i --
            }
          }
        }

        this.dialogmenuList = res.rows
      },
      //打开dialog
      openDialog(param){
          this.menuDialog = true
          this.initModel()
          this.$nextTick(()=>{
            this.$refs.dialogForm.clearValidate();
          })
          param.menuList.forEach(item=>{
            this.currentChosrMenu.push(item.menuId)
          })
          this.getDialogmenuList(param)
      },
      //关闭dialog
      closeDialog () {
          this.menuDialog = false
      },
      //添加菜单
      async confirmAddMenu () {
        formValid(this, 'dialogForm', this.saveFn)
      },
      //保存菜单
      async saveMenu (data) {
        console.log(data)
        let res = await Port.apiMenuGroupEdit({
          enterpriseid:this.$route.query.key,
          ...data
        })
        requestTips(res,()=>{
          this.getInfo()
          this.menuDialog = false
        })
      },
      async saveFn () {
        let res = await Port.apiMenuGroupAdd({
          enterpriseid:this.$route.query.key,
          ...this.dialogFormModel
        })
        requestTips(res,()=>{
          this.getInfo()
          this.menuDialog = false
        })
      },
      //删除
      async deleteMenu (item) {
        askDialog("确认删除？",async () => {
            const res = await Port.apiMenuGroupDel({menuId:item.menuId,enterpriseid:this.$route.query.key});
            requestTips(res,()=>{
              this.getInfo()
            })
        })
      },
      async getSelectName(){
        let data = this.dialogmenuList.find(item => this.dialogFormModel.secondMenu == item.primaryKey)
        this.dialogFormModel.menuName = data.name
        this.dialogFormModel.menuId = data.primaryKey
        let res = await Port.apiMenuSonList({
          enterpriseid:this.$route.query.key,
          parentId:this.dialogFormModel.secondMenu
        })
        this.secondMenuList = res.rows || []
      },
      //checkbox组变化时
      handleMenusChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.dialogmenuList.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.dialogmenuList.length;
      },
      initModel () {
        this.dialogFormModel.secondMenu = ""
        this.dialogFormModel.menuName = ""
        this.dialogFormModel.secondLevelMenuList = []
        this.dialogFormModel.ifInMore = 0
      }
  },
};
</script>
<style lang="scss" scoped>
.menu-out {
  padding: 10px 25px;
  .el-collapse {
    border: none;
  }
  .collapse-title {
    width: 100%;
    padding-left: 20px;
    span {
      font-size: 16px;
    }
  }
  .el-collapse-item {
    margin-bottom: 15px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  .form-box {
    width: 100%;
    border-top: 1px solid #ebeef5;
    padding: 20px 20px 0 20px;
    .item-btn {
      margin-top: 3px;
    }
  }
  .tag-item{
      margin: 0 20px 15px 0;
  }
  .null-page {
    line-height: 100px;
  }
  .el-checkbox{
      margin-bottom: 15px;
  }
}
</style>